package com.efounder.form.comp.shoppingcar;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.View;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.base.data.ESPRowSet;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.base.DataComponent;
import com.efounder.form.comp.shoppingshow.ShoppingShow;
import com.efounder.form.model.Column;
import com.efounder.form.model.JSONFormModel;
import com.efounder.form.model.ShoppingCarFormModel;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.message.db.MessageDBManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.R;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by XinQing on 2016/10/13.
 */

public class ShoppingUtils {
    public ShoppingUtils() {
        super();
        Log.i("","");
    }

    public JSONFormModel mergeFormModel(JSONFormModel jsonFormModel, ShoppingCarFormModel shoppingCarFormModel, String shoppingCarKey) {
        EFDataSet billDataSet = jsonFormModel.getFormDataModel().getBillDataSet();
        List<ESPRowSet> rowSetList = billDataSet.getRowSetList();
        EFRowSet billRowSet = (EFRowSet) rowSetList.get(0);

        EFDataSet mergedDataSet = new EFDataSet();
        HashMap<String, EFDataSet> shoppingCarDataSetMap = shoppingCarFormModel.getFormDataModel().getDataSetMap();
        for (String key : shoppingCarDataSetMap.keySet()) {
            EFDataSet shoppingCarDataSet = shoppingCarDataSetMap.get(key);
            mergedDataSet.addAll(shoppingCarDataSet);
        }
        //将mergedDataSet放入billRowSet下级
        billRowSet.setDataSet(shoppingCarKey, mergedDataSet);
        //test
//        String json = jsonFormModel.convert2DataJSON();
        return jsonFormModel;
    }

    public JSONFormModel testScript(ShoppingCarFormModel shoppingCarFormModel) {
        HashMap<String, EFDataSet> shoppingCarDataSetMap = shoppingCarFormModel.getFormDataModel().getDataSetMap();
        Set<String> keySet= shoppingCarDataSetMap.keySet();
        while (keySet.iterator().hasNext()){
            String key = keySet.iterator().next();
            EFDataSet shoppingCarDataSet = shoppingCarDataSetMap.get(key);
        }

        return null;
    }

    //XXX 测试方法
    public boolean sendFormMessage(int userID, String messageString) {
        Log.i("", "");
//        return JFMessageManager.getInstance().sendFormMessage(userID,messageString);
        return true;
    }


    public String getEnvironmentValue(String arg1) {
        String value = EnvironmentVariable.getProperty(arg1,"");
        return value;
    }



//    Handler handler2 = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            EFFrameUtils.getCurrentActivity().finish();
//        }
//    };



    public void gotoChatAfterConfirm() {

        //handler2.sendEmptyMessage(0);
        EFFrameUtils.getCurrentActivity().finish();

    }

    public String getSelfName() {
        return EFAppAccountUtils.getNickName();
    }

    public void gotoChat() {
        //3.跳转到聊天界面
        Bundle bundle = EFFrameUtils.getCurrentActivity().getIntent().getExtras();
        bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_LEFT_VISIBILITY, View.VISIBLE);
        bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_RIGHT_VISIBILITY, View.INVISIBLE);
        bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME, bundle.getString("nickName"));
        try {
            EFFrameUtils.pushFragment((Class<? extends Fragment>) Class.forName(AppContext.getInstance()
                    .getResources().getString(R.string.PUBLIC_CHAT_FRAGMENT_PACKAGE_NAME)) , bundle);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void log(String level, String log) {
        if ("d".equals(level)) {
            Log.d("js-----", log);
        }else if ("i".equals(level)) {
            Log.i("js-----", log);
        } else if ("w".equals(level)) {
            Log.w("js-----", log);
        } else if ("e".equals(level)) {
            Log.e("js-----", log);
        } else {
            Log.i("js-----", log);
        }
    }


    /**
     * 根据消息id查询消息
     *
     * @param msgID
     * @return
     */
    public IMStruct002 queryMessageStruct(String msgID) {
       // MessageDBHelper dbHelper = new MessageDBHelper(AppContext.getCurrentActivity());
        MessageDBManager dbManager = MessageDBManager.getInstance();
        IMStruct002 struct002 = dbManager.queryForID(msgID);
        return struct002;
    }

    /**
     * 更新消息
     *
     * @param struct002
     */
    public void updateMessageStruct(IMStruct002 struct002) {
//        MessageDBHelper dbHelper = new MessageDBHelper(AppContext.getCurrentActivity());
//        MessageDBManager dbManager = new MessageDBManager(dbHelper);
        MessageDBManager dbManager = MessageDBManager.getInstance();

        dbManager.update(struct002);
    }


    /**
     * @param shoppingCar
     * @return
     */
    public boolean isNULLForShoppingCar(ShoppingCar shoppingCar) {
        ShoppingCarFormModel shoppingCarFormModel = (ShoppingCarFormModel) shoppingCar.getDataSetComponent();

        Map<String, EFDataSet> dataSetMap = shoppingCarFormModel.getFormDataModel().getDataSetMap();
        if (dataSetMap == null || dataSetMap.size() == 0) {
            ToastUtil.showToast(AppContext.getCurrentActivity(), "请选择商品");
            return true;
        }

        for (Map.Entry<String, EFDataSet> entry : dataSetMap.entrySet()) {
            EFDataSet efDataSet = entry.getValue();
            List<EFRowSet> efRowSetList = efDataSet.getRowSetArray();
            if (efRowSetList == null) return true;
            /**得到count的位置**/
            String dataSetColID = "";
            List<DataComponent> columnList = shoppingCar.getColumnModel().getChildren();
            for (int i = 0; i < columnList.size(); i++) {
                Column column = (Column) columnList.get(i);
                if ("count".equals(column.getComponentType())) {
                    dataSetColID = column.getDataSetColID();
                    break;
                }
            }
            /*****/
            for (int i = 0; i < efRowSetList.size(); i++) {
                EFRowSet efRowSet = efRowSetList.get(i);
                String value = efRowSet.getString(dataSetColID, "").trim();
                if (value.equals("")) {
                    ToastUtil.showToast(AppContext.getCurrentActivity(), "请填写商品数量");
                    return true;
                }else if (Double.parseDouble(value) <= 0){
                    ToastUtil.showToast(AppContext.getCurrentActivity(), "商品数量必须大于0");
                    return true;
                }
            }
        }

        return false;

    }
    /**
     * @param shoppingShow
     * @return
     */
    public boolean isNULLForShoppingShow(ShoppingShow shoppingShow) {
        JSONFormModel shoppingCarFormModel = (JSONFormModel) shoppingShow.getDataSetComponent();

        Map<String, EFDataSet> dataSetMap = shoppingCarFormModel.getFormDataModel().getDataSetMap();
        if (dataSetMap == null || dataSetMap.size() == 0) {
            ToastUtil.showToast(AppContext.getCurrentActivity(), "单据出现问题。");
            return true;
        }

        for (Map.Entry<String, EFDataSet> entry : dataSetMap.entrySet()) {
            if (entry.getKey().equals(shoppingShow.getDataSet().getTableName())) {
                // } else {
                EFDataSet efDataSet = entry.getValue();
                List<EFRowSet> efRowSetList = efDataSet.getRowSetArray();
                if (efRowSetList == null) return true;
                /**得到count的位置**/
                String dataSetColID = "";
                boolean isShow = false;
                String priceDataSetColID = "";
                boolean isShowPrice = false;
                List<DataComponent> columnList = shoppingShow.getColumnModel().getChildren();
                for (int i = 0; i < columnList.size(); i++) {
                    Column column = (Column) columnList.get(i);
                    if ("count".equals(column.getComponentType())) {
                        dataSetColID = column.getDataSetColID();
                        isShow = column.isVisible();
                    }
                    if("price".equals(column.getComponentType())){
                        priceDataSetColID = column.getDataSetColID();
                        isShowPrice = column.isVisible();
                    }
                }
                /***一般情况efRowSetList只有一行rowset**/
                for (int i = 0; i < efRowSetList.size(); i++) {
                    EFRowSet efRowSet = efRowSetList.get(i);
                    //购物车明细
                    Map<String, EFDataSet> gwcMXdataSetMap  = efRowSet.getDataSetMap();
                    if(gwcMXdataSetMap==null) {
                        ToastUtil.showToast(AppContext.getCurrentActivity(), "请选择商品");
                        return true;
                    }
                    for (Map.Entry<String, EFDataSet> gwcentry : gwcMXdataSetMap.entrySet()) {
                        EFDataSet gwcDataSet = gwcentry.getValue();
                        List<EFRowSet> gwcRowSetList = gwcDataSet.getRowSetArray();
                        /*****购物车明细可能是多行rowset*****/
                        if(gwcRowSetList==null||gwcRowSetList.size()==0) {
                            ToastUtil.showToast(AppContext.getCurrentActivity(), "请选择商品");
                            return true;
                        }
                        for (int k = 0; k < gwcRowSetList.size(); k++) {
                            EFRowSet mxefRowSet = gwcRowSetList.get(k);
                            if (isShow) {
                                String value = mxefRowSet.getString(dataSetColID, "").trim();
                                if (value.equals("")) {
                                    ToastUtil.showToast(AppContext.getCurrentActivity(), "请填写商品数量");
                                    return true;
                                } else if (Double.parseDouble(value) <= 0) {
                                    ToastUtil.showToast(AppContext.getCurrentActivity(), "商品数量必须大于0");
                                    return true;
                                }
                            }
                            if (isShowPrice) {
                                String value = mxefRowSet.getString(priceDataSetColID, "").trim();
                                if (value.equals("")) {
                                    ToastUtil.showToast(AppContext.getCurrentActivity(), "请填写商品价格");
                                    return true;
                                } else if (Double.parseDouble(value) <= 0) {
                                    //ToastUtil.showToast(AppContext.getCurrentActivity(), "商品价格必须大于0");
                                    return true;
                                }
                            }

                        }

                    }

                }
            }
        }

        return false;

    }

    public static final String BROADCAST_ACTION_REFRESH_CHAT = "com.efounder.broadcast:refreshChat";

    public void sendBroadcastRefreshChat(){
        Intent intent = new Intent(BROADCAST_ACTION_REFRESH_CHAT);
        AppContext.getInstance().sendBroadcast(intent);
    }

}
